package com.javaxiaobear.base.framework.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.math.BigInteger;

public class BigIntegerSerializer extends StdSerializer<BigInteger> {

  public static final BigInteger LOW = BigInteger.valueOf(-9007199254740991L);
  public static final BigInteger HIGH = BigInteger.valueOf(9007199254740991L);
  public static final BigIntegerSerializer instance = new BigIntegerSerializer();

  protected BigIntegerSerializer() {
    super(BigInteger.class);
  }

  @Override
  public void serialize(BigInteger value, JsonGenerator gen, SerializerProvider provider)
      throws IOException {
    if (value == null) {
      gen.writeNull();
    } else {
      String str = value.toString();
      if (str.length() < 16 || value.compareTo(LOW) >= 0 && value.compareTo(HIGH) <= 0) {
        gen.writeNumber(str);
      } else {
        gen.writeString(str);
      }
    }
  }
}
